using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EngineObject : PartObject
{
    public float realPower { 
        get { return m_Power; }
        set {
            float newValue = Mathf.Clamp(value, -1f, 1f);
            m_Power = newValue;
        }
    }
    public float m_Scale =1;
    public float m_Power=0;
    public ParticleSystem m_Smoke;
    public ParticleSystem m_Flame;
    public ConstantForce2D m_ConstantForce;
    public Engine.EngineType m_EngineType;

    public float m_StartSizeMax = 1.5f;
    public float m_StartSpeedMax = 3;
    public float m_StartSizeMin = 1;
    public float m_StartSpeedMin = 2;
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        Engine engine = m_Part as Engine;
        if (engine == null)
            return;
        m_Scale = engine.scale;
        var enginePowerScale = engine.power / engine.powerMax;
        var enginePowerChange = enginePowerScale - realPower;
        if (Mathf.Abs(enginePowerChange) > 0.01 && realPower != 0)
        {
            float closeRate = 5;
            if (enginePowerChange > 0)
                closeRate = 1;
            realPower = realPower + enginePowerChange / Mathf.Abs(enginePowerChange) * Time.deltaTime * closeRate;
        }
        else
        {
            realPower = engine.power;
        }
        engine.power = 0;
    }
    private void FixedUpdate()
    {
        //if (!IsChanged)
        //    return;
        //IsChanged = false;
        ParticleSystem.MainModule main;
        if (m_Flame)
        {
            main = m_Flame.main;
            main.startSize = (m_StartSizeMax * m_Scale - m_StartSizeMin * m_Scale) * realPower + m_StartSizeMin * m_Scale;
            main.startSpeed = (m_StartSpeedMax * m_Scale - m_StartSpeedMin * m_Scale) * realPower + m_StartSpeedMin * m_Scale;
        }
        ParticleSystem.MainModule smokeMain;
        if (m_Smoke)
            smokeMain = m_Smoke.main;
        if (realPower == 0)
        {
            if (m_Flame)
                main.loop = false;
            if (m_Smoke)
            smokeMain.loop = false;
        }
        else
        {
            if (m_Flame)
                main.loop = true;
            if (m_Smoke)
                smokeMain.loop = true;
            if(m_Flame && !m_Flame.isPlaying)
                m_Flame.Play();
            if (m_Smoke && !m_Smoke.isPlaying)
                m_Smoke.Play();
        }
        if(m_ConstantForce && m_Part != null)
        {
            Engine engine = m_Part as Engine;
            var force = m_ConstantForce.relativeForce;
            force.y = engine.powerMax * realPower;
            m_ConstantForce.relativeForce = force;
        }
    }
}
